package com.ghy.service.impl;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.core.util.ObjectUtil;
import com.ghy.constant.ML;
import com.ghy.exception.ServiceException;
import com.ghy.mapper.RoleMapper;
import com.ghy.mapper.RoleMenuMapper;
import com.ghy.vo.MenuSimpleListVO;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ghy.entity.Menu;
import com.ghy.mapper.MenuMapper;
import com.ghy.service.MenuService;
import com.ghy.dto.MenuInsertDTO;
import com.ghy.dto.MenuPageDTO;
import com.ghy.dto.MenuUpdateDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.ghy.entity.table.MenuTableDef.MENU;
import static com.ghy.entity.table.RoleMenuTableDef.ROLE_MENU;

/**
 * 开发菜单表 服务层实现。
 *
 * @author ghy
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "menu")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>  implements MenuService{

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @CacheEvict(allEntries = true)// 缓存逐出
    @Override
    public boolean insert(MenuInsertDTO dto) {
        Menu menu = BeanUtil.copyProperties(dto, Menu.class);

        //父菜单赋值
        if (ObjectUtil.isNull(dto.getPid())) {
            menu.setPid(ML.Menu.ROOT_ID);
            menu.setUrl("");

        }

        //标题不能重复
        if(QueryChain.of(mapper)
                .where(MENU.TITLE.eq(menu.getTitle()))
                .exists()){
            throw new ServiceException("菜单标题已存在");
        }
        menu.setCreated(LocalDateTime.now());
        menu.setUpdated(LocalDateTime.now());
        return mapper.insert(menu) > 0;

    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Menu select(Long id) {
        return QueryChain.of(mapper)
                .where(MENU.ID.eq(id))
                .withRelations()
                .one();
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(MenuUpdateDTO dto) {

        //标题查重
        if (QueryChain.of(mapper)
                .where(MENU.TITLE.eq(dto.getTitle()))
                .and(MENU.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("菜单标题已存在");
        }
        //组装 entity 实体类
        Menu menu = BeanUtil.copyProperties(dto, Menu.class);
        menu.setUpdated(LocalDateTime.now());
        return UpdateChain.of(menu)
                .where(MENU.ID.eq(menu.getId()))
                .update();
    }


    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {

        // 查询父菜单ID和全部子菜单ID
        // select id from menu where pid = 1 or id = 1
        List<Long> ids = QueryChain.of(mapper)
                .select(MENU.ID)
                .where(MENU.PID.eq(id))
                .or(MENU.ID.eq(id))
                .objListAs(Long.class);

        // 删除中间表记录
        // delete from role_menu where fk_menu_id in(?)
        UpdateChain.of(roleMenuMapper)
                .where(ROLE_MENU.FK_MENU_ID.in(ids))
                .remove();

        // 删除 MENU 表中的菜单
        // delete from menu where id in(?)
        return UpdateChain.of(mapper)
                .where(MENU.ID.in(ids))
                .remove();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {

        // 查询父菜单ID和全部子菜单ID
        // select id from menu where pid = 1 or id = 1
        List<Long> idss = QueryChain.of(mapper)
                .select(MENU.ID)
                .where(MENU.PID.in(ids))
                .or(MENU.ID.in(ids))
                .objListAs(Long.class);

        // 删除中间表记录
        // delete from role_menu where fk_menu_id in(?)
        UpdateChain.of(roleMenuMapper)
                .where(ROLE_MENU.FK_MENU_ID.in(idss))
                .remove();

        // 删除 MENU 表中的菜单
        // delete from menu where id in(?)
        return UpdateChain.of(mapper)
                .where(MENU.ID.in(idss))
                .remove();
    }

    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", unless = "#result == null")
    @Override
    public Page<Menu> page(MenuPageDTO dto) {
        QueryChain<Menu> queryChain = QueryChain.of(mapper);
        queryChain.orderBy(MENU.PID.asc(), MENU.IDX.asc(), MENU.ID.desc());

        //pid条件
        Long  pid = dto.getPid();
        if(ObjectUtil.isNotNull(pid)){
            queryChain.where(MENU.PID.eq(pid));
        }

        //title条件
        String title = dto.getTitle();
        if(ObjectUtil.isNotNull(title)){
            queryChain.where(MENU.TITLE.like(title));
        }
        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(),dto.getPageSize()));
    }

    @Cacheable(key = "#root.methodName",
            unless = "#result == null")
    @Override
    public List<MenuSimpleListVO> simpleList() {
        //查询所有菜单
        List<Menu> menus = QueryChain.of(mapper)
                .orderBy(MENU.PID.asc(), MENU.IDX.asc(), MENU.ID.desc())
                .withRelations()
                .list();
        //组装 VO 实体类
        List<MenuSimpleListVO> menuSimpleListVOS = new ArrayList<>();
        menus.forEach(menu -> {
            MenuSimpleListVO menuSimpleListVO = BeanUtil.copyProperties(menu, MenuSimpleListVO.class);
            if (menu.getParentMenu() != null) {
                menuSimpleListVO.setParentTitle(menu.getParentMenu().getTitle());
            }
            menuSimpleListVOS.add(menuSimpleListVO);
        });
        return menuSimpleListVOS;
    }


}
